<template>
  <section class="todoapp">
    <TodoHeader @add="handleAdd"></TodoHeader>
    <TodoMain
      :list="list2"
      @del="handleDel"
      @state="handleState"
      @changeAll="handleAll"
    ></TodoMain>
    <TodoFooter
      :list="list"
      @delCompleted="handleClear"
      :flag="flag"
      @changeFlag="(val) => { flag = val }"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  // 注册组件
  components: { TodoHeader, TodoMain, TodoFooter },
  // 定义数据
  data () {
    return {
      // list: [
      //   { id: 12, name: '吃饭', isDone: false },
      //   { id: 14, name: '听歌', isDone: true },
      //   { id: 23, name: '洗澡', isDone: true },
      //   { id: 34, name: '睡觉', isDone: false },
      //   { id: 35, name: '游戏', isDone: false },
      // ],
      list: JSON.parse(localStorage.getItem('todo')) || [],
      flag: 1 // 1 显示全部任务； 2 显示进行中； 3 显示已完成
    }
  },
  // 定义方法
  methods: {
    handleDel (id) {
      // console.log(id)
      this.list = this.list.filter(item => item.id != id)
    },
    handleAdd (todoname) {
      // console.log(todoname)
      this.list.unshift({ 
        id: Date.now(), 
        name: todoname, 
        isDone: false 
      })
    },
    handleState (id) {
      // console.log(id)
      let res = this.list.find(item => item.id == id)
      res.isDone = !res.isDone
    },
    handleClear () {
      this.list = this.list.filter(item => item.isDone === false)
    },
    handleAll (val) {
      // console.log(val)
      this.list.forEach(item => {
        item.isDone = val
      })
    }
  },
  // 计算属性
  computed: {
    list2 () {
      if (this.flag === 1) {
        return this.list
      } else if (this.flag === 2) {
        return this.list.filter(item => item.isDone === false)
      } else {
        return this.list.filter(item => item.isDone === true)
      }
    }
  },
  // 侦听器
  watch: {
    list: {
      handler (val) {
        localStorage.setItem('todo', JSON.stringify(val))
      },
      deep: true
    }
  }
}
</script>

<style></style>
